﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using FirstFloor.ModernUI.Windows.Controls;
using YanMsg.APCode;


namespace YanMsg.View
{
    /// <summary>
    /// MsgBox.xaml 的交互逻辑
    /// </summary>
    public partial class FileBox : System.Windows.Controls.UserControl
    {

        public  ObservableCollection<YanChat_ServerFileType> ObcFileType = new ObservableCollection<YanChat_ServerFileType>();
        private  ObservableCollection<YanChat_ServerFile> ObcFiles = new ObservableCollection<YanChat_ServerFile>();
        private  ObservableCollection<YanChat_ServerFile> ListDownLoadFiles = new ObservableCollection<YanChat_ServerFile>();
        private  List<YanChat_ServerFile> ListFiletemp = new List<YanChat_ServerFile>();

        string strUserName = "";

        public FileBox(string strMagUser)
        {
            strUserName = strMagUser;
            ListFiletemp = new YanChat_ServerFileB().GetEntities(d => d.CrUser == strUserName).ToList();
            InitializeComponent();
            ObcFileType = new YanChat_ServerFileTypeB().GetEntities(d => d.CrUser == strUserName).ToObservableCollection();
            this.ListFileType.ItemsSource = ObcFileType;
            ObcFileType.Insert(0, (new YanChat_ServerFileType { id = -1, TypeName = "全部文件" }));
        }




        /// <summary>
        /// 根据通知类别查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListFileType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var FileType = (YanChat_ServerFileType)ListFileType.SelectedItem;
            if (FileType != null)
            {
                //没有正在上传的文件不用刷新数据集
                if (ObcFiles.Where(d => d.Remark1 != d.FileSize).Count() == 0)
                {
                    if (FileType.id != -1)
                    {
                        ObcFiles = ListFiletemp.Where(d => d.FileTypeID == FileType.id).OrderByDescending(d => d.Crdate).ToObservableCollection();
                    }
                    else
                    {
                        ObcFiles = ListFiletemp.Where(d => d.CrUser == strUserName).OrderByDescending(d=>d.Crdate).ToObservableCollection();
                    }
                    this.ListFileS.ItemsSource = ObcFiles;
                }
                else
                {
                    MsgManger.Show("有正在上传的文件,不能查看其它类型文件");
                }
            }


        }
        //上传文件
        private void BtaddFile_Click(object sender, RoutedEventArgs e)
        {

            UploadFile();
        }

        //添加类型
        private void addFileType_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                
                YanChat_ServerFileType newtype = new YanChat_ServerFileType();
                newtype.TypeName = tbTypeName.Text;
                newtype.CrDate = DateTime.Now;
                newtype.CrUser = strUserName;
                newtype.TypePid = 0;
                new YanChat_ServerFileTypeB().Insert(newtype);
                ObcFileType.Add(newtype);
                tbTypeName.Text = "";
            }
            catch (Exception ex)
            {

            }


        }

        private void ListFileS_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ListFileS.SelectedItems.Count > 0)
            {
                btDownLoad.Visibility = Visibility.Visible;
                btDelFile.Visibility = Visibility.Visible;
                btShare.Visibility = Visibility.Visible;
            }
            else
            {
                btDownLoad.Visibility = Visibility.Hidden;
                btDelFile.Visibility = Visibility.Hidden;
                btShare.Visibility = Visibility.Hidden;

            }
            tbSelCount.Text = ListFileS.SelectedItems.Count.ToString();
        }

        //下载
        private void btDownLoad_Click(object sender, RoutedEventArgs e)
        {
            DownLoadFile();
        }

        //打开文件夹
        private void BtOpen_Click(object sender, RoutedEventArgs e)
        {
            string foldPath = BtOpen.Tag.ToString();
            System.Diagnostics.Process.Start("Explorer.exe", foldPath);
        }

        //右键菜单上传文件
        private void MenuUploadFile_Click(object sender, RoutedEventArgs e)
        {
            UploadFile();
        }

        private void MenuUpdateFileType_Click(object sender, RoutedEventArgs e)
        {
            YanChat_ServerFileType UpdateItem = ListFileType.SelectedItem as YanChat_ServerFileType;
        }

        //删除类型
        private void MenuDelFileType_Click(object sender, RoutedEventArgs e)
        {
            YanChat_ServerFileType delItem = ListFileType.SelectedItem as YanChat_ServerFileType;
            if (ObcFiles.Count() > 0)
            {
                MsgManger.Show("该文件类型中还存在文件，不能删除");
            }
            else
            {
                ObcFileType.Remove(delItem);
                new YanChat_ServerFileTypeB().Delete(delItem);
            }

        }

        //禁用右键选中
        private void ListFileS_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void MenuDownLoadFile_Click(object sender, RoutedEventArgs e)
        {
            DownLoadFile();
        }

        //右键删除文件
        private void MenuDelFile_Click(object sender, RoutedEventArgs e)
        {
            delFile();
        }
        //删除文件
        private void btDelFile_Click(object sender, RoutedEventArgs e)
        {
            delFile();
        }

        private void UploadFile()
        {
            try
            {
                YanChat_ServerFileType FileType = (YanChat_ServerFileType)ListFileType.SelectedItem;
                if (FileType != null&&FileType.id!=-1)
                {
                    System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
                    ofd.Multiselect = true;
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        try
                        {
                            foreach (string FileName in ofd.FileNames)
                            {
                                FileInfo File = new FileInfo(FileName.ToString());
                                YanChat_ServerFile NewFile = new YanChat_ServerFile();
                                NewFile.FileTypeID = FileType.id;
                                NewFile.FileName = File.Name;
                                NewFile.FileVision = "0";
                                NewFile.CrUser = strUserName;
                                NewFile.Crdate = DateTime.Now;
                                ObcFiles.Insert(0, NewFile);
                                ListFiletemp.Add(NewFile);
                            }
                            Task UPloadTask = new Task(() =>
                            {
                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    //UPloadTaskMethod(ofd.FileNames, FileType.id);
                                    foreach (string FileName in ofd.FileNames)
                                    {
                                        YanChat_ServerFile UpdateFile = ObcFiles.First(d => FileName.Contains(d.FileName) && string.IsNullOrEmpty(d.FileCode));
                                        new UpDownLoadFile().UpLoadFile(FileName,  ConfigManger.ClientFileCenterUrl  , ref UpdateFile);
                                        new YanChat_ServerFileB().Insert(UpdateFile);
                                    }
                                }));
                            });
                            UPloadTask.Start();
                        }
                        catch (Exception ex)
                        {
                            MsgManger.Show(ex.Message.ToString());
                        }
                    }
                }
                else
                {
                    MsgManger.Show("请先新建文件类型后再上传文件！");

                }
            }
            catch (Exception)
            {
                
                throw;
            }



        }


        private void DownLoadFile()
        {
            try
            {
                if (ListFileS.SelectedItems.Count > 0)
                {
                    FolderBrowserDialog dialog = new FolderBrowserDialog();
                    dialog.Description = "请选择文件路径";
                    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        IQueryable ListDownLoadFiles = ListFileS.SelectedItems.AsQueryable();
                        stToolbar.Visibility = Visibility.Visible;
                        Task UPloadTask = new Task(() =>
                        {
                            this.Dispatcher.Invoke(new Action(() =>
                            {
                                string foldPath = dialog.SelectedPath;
                                foreach (YanChat_ServerFile item in ListDownLoadFiles)
                                {
                                    UpDownLoadFile.DownLoadFile(ConfigManger.ClientFileCenterUrl + item.FileCode, foldPath + "\\" + item.FileName, PrbDownLoad);
                                }
                                BtOpen.Visibility = Visibility.Visible;
                                BtOpen.Tag = foldPath;
                                ListFileS.UnselectAll();
                            }));
                        });
                        UPloadTask.Start();
                    }
                }
                else
                {
                    MsgManger.Show("请选定文件后再下载");
                }

            }
            catch (Exception)
            {

            }
        }


        private void delFile()
        {
            try
            {
                var result = ModernDialog.ShowMessage("确认要删除这" + ListFileS.SelectedItems.Count + "个文件?", "提示", MessageBoxButton.YesNo);
                //确定后删除该消息
                if (result.ToString() == "Yes")
                {
                    List<int> ListDelIDs = new List<int>();
                    foreach (YanChat_ServerFile item in ListFileS.SelectedItems)
                    {
                        ListDelIDs.Add(item.id);
                    }

                    foreach (int id in ListDelIDs)
                    {
                        ObcFiles.Remove(ObcFiles.FirstOrDefault(d => d.id == id));
                        ListFiletemp.Remove(ListFiletemp.FirstOrDefault(d => d.id == id));
                        new YanChat_ServerFileB().Delete(d => d.id == id);
                    }
                }
            }
            catch (Exception)
            {
                
            }

        }
    }
}
